package task;
import java.util.Date;;

/**
 *
 * @author pdv
 *
 */
public abstract class Worker extends Thread {
	
	private Object lock = new Object();

	private TaskQueue queue = new TaskQueue();
	private TaskQueue hiqueue= new TaskQueue();
	
	private volatile boolean stopped = false;
	
	public Worker() {
		super();
	}
	/**
	 *
	 */
	public void terminate() {
		this.stopped = true;
		synchronized (lock) {
			lock.notify();
		}
	}
	
	public void run() {
//		while (!stopped) {
//			Task task = null;
//			while ((task = this.queue.retriveTask()) == null) {
//				try {
//					//System.out.println("task is null");
//					synchronized (lock) {
//						/**
//						 * sleep at most 10 sec, and then check stop
//						 */
//						
//						lock.wait();
//						
//					}
//					if (this.stopped)
//						return;
//					
//				} catch (InterruptedException e) {
//					System.out.println(" exception");
//					Thread.interrupted();
//					
//					break;
//				}
//			}
		while (!stopped) {
			
			Task hitask = null;
			Task task=null;
			
			hitask = this.hiqueue.retriveTask();
			if(hitask!=null){
				processTask(hitask);
			}else{
				task= this.queue.retriveTask();
				if (task!=null){
					processTask(task);
				}else{
					try {
						//System.out.println("task is null");
						synchronized (lock) {
							/**
							 * sleep at most 10 sec, and then check stop
							 */
							
							lock.wait();
							
						}
						if (this.stopped)
							return;
						
					} catch (InterruptedException e) {
						System.out.println(" exception");
						Thread.interrupted();
						
						break;
					}
				}
			}
			try {
				sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
				
		
	}
	
	protected abstract void processTask(Task task);
	
	/**
	 *
	 * @param task
	 */
	public void feedTask(Task task) {
		this.queue.feedTask(task);
		synchronized (lock) {
			lock.notify();
		}
	}
	public void feedHiTask(Task task){
		this.hiqueue.feedTask(task);
		synchronized (lock) {
			lock.notify();
		}
	}
	public void setMaxLen(int maxlen){
		this.queue.setMaxLen(maxlen);
		this.hiqueue.setMaxLen(maxlen);
	}
	
}
